package com.szjz.elasticsearch.eshelper.aop;

import com.szjz.elasticsearch.eshelper.property.ESRestClientProperties;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.math.BigDecimal;

/**
 * @author 史博
 * @desc 时间切面 用于计算查询的时间 debug模式下开启
 * @date 2020/5/12
 */
@Slf4j
@Configuration
@Aspect
public class TimeAspect {

    @Autowired
    private ESRestClientProperties esRestClientProperties;

    /**
     * 开始时间
     */
    private Long startTime;
    /**
     * 结束时间
     */
    private Long endTime;

    @Pointcut(
            "execution(* com..*.BaseESServiceImpl.*(..)) && " +
                    "!execution(* com..*.BaseESServiceImpl.saveBatchByOne(..)) && " +
                    "!execution(* com..*.BaseESServiceImpl.scheduled(..))"
    )
    private void anyMethod() {
    }

    @Before("anyMethod()")
    public void before() {
        if (esRestClientProperties.getDebug()) {
            startTime = System.nanoTime();
        }
    }

    @After("anyMethod()")
    public void after(JoinPoint jp) {
        if (esRestClientProperties.getDebug()) {
            MethodSignature methodSignature = (MethodSignature) jp.getSignature();
            Method method = methodSignature.getMethod();
            endTime = System.nanoTime();
            BigDecimal divide = BigDecimal.valueOf((endTime - startTime)).divide(BigDecimal.valueOf(1000000000));
            log.warn("==== 执行方法：{}  共耗时：{}", method.getName(), divide);
        }
    }

}
